﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TBlog.Web.Models;
using TBlog.Web.Service;
using TBlog.Web.ViewModel;

namespace TBlog.Web.Controllers
{
    public class ArticleController : BaseController
    {
        ICategoryService _categoryservice;
        IArticleService _articleservice;
        public ArticleController(IArticleService articleservice, ICategoryService categoryservice)
        {
            _categoryservice = categoryservice;
            _articleservice = articleservice;
        }
        /// <summary>
        /// 获取文章列表
        /// </summary>
        /// <returns></returns>
        public ActionResult GetListArticle(int pageindex = 1, int pagesize = 10)
        {
            //var pageindex = Request["pageindex"];
            //var pagesize = Request["pagesize"];
            var model = _articleservice.GetArticleList(a => a.ID == a.ID, new Common.PageHelper.PageListRequest(pageindex, pagesize, true));
            ViewBag.Categories = _categoryservice.GetCategory(a => a.ID == a.ID, new Common.PageHelper.PageListRequest(pageindex, pagesize, true)).Items;
            return View("ArticleList", model);
        }
        [HttpGet]
        public ActionResult Create()
        {
            ViewBag.Categories = _categoryservice.GetCategory(a => a.ID == a.ID, new Common.PageHelper.PageListRequest(1, 10, true)).Items;
            return View();
        }
        [HttpPost]
        [ValidateAntiForgeryToken]
        [ValidateInput(false)]
        public ActionResult Create(ViewArticle model)
        {
            var entity = new Article()
            {
                Title = model.Title,
                Author = model.Author,
                Tags = model.Tags,
                CategoryID = model.CategoryID,
                Content = model.Content,
                State = model.State,
                CreateTime = DateTime.Now,

            };
            _articleservice.Add(entity);
            return RedirectToAction("GetListArticle", "Article");
            //return Json(_articleservice.GetJsonMessage(true, "", "创建成功"));
        }
        [HttpGet]
        public ActionResult Edit()
        {
            var ID = Convert.ToInt32(Request["articleid"]);
            var model = _articleservice.GetByID(ID);
            ViewBag.Category = _categoryservice.GetAll().ToList();
            return View(model);
        }
        [ValidateAntiForgeryToken]
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Edit(Article model)
        {
            var entity = _articleservice.GetByID(model.ID);
            entity.Title = model.Title;
            entity.Author = model.Author;
            entity.CategoryID = model.CategoryID;
            entity.Content = model.Content;
            entity.Hits = model.Hits;
            entity.State = model.State;
            entity.Tags = model.Tags;

            _articleservice.Update(entity);
            return RedirectToAction("GetListArticle", "Article");
            //return View();
        }
        public ActionResult Delete(int ID)
        {
            _articleservice.Delete(ID);
            return RedirectToAction("GetListArticle", "Article");
        }

        [HttpPost]
        public ActionResult UploadImage(HttpPostedFileBase f)
        {

            var files = Request.Files;

            if (files.Count == 0)
            {
                var json = new
                {
                    code = 1,
                    msg = "没有找到要上传的文件呢，请重新选择吧。"
                };
                return Json(json);
            }
            try
            {
                var curFile = files[0];
                //扩展文件夹 e.g. /2016/10/
                var extPath = DateTime.Now.Year.ToString() + "/" + DateTime.Now.Month.ToString() + "/";
                //获取图片文件保存的完整路径
                var fileSavePath = Server.MapPath("~/uploads/images/" + extPath);
                //路径不存在则创建
                if (!Directory.Exists(fileSavePath))
                    Directory.CreateDirectory(fileSavePath);

                //获取文件名
                var fileName = Path.GetFileName(curFile.FileName);
                //获取文件后缀名
                var filePostfixName = fileName.Substring(fileName.LastIndexOf('.'));
                //获取新文件名
                var newFileName = DateTime.Now.ToString("yyyyMMddHHmmss") + filePostfixName;
                //合并路径
                var path = Path.Combine(fileSavePath, newFileName);
                //保存文件
                curFile.SaveAs(path);

                var resourcesSystemUrl = ConfigurationManager.AppSettings["ResourcesSystemUrl"];

                return Json(new
                {
                    code = 0,
                    msg = "咦？好像上传成功了呢。",
                    data = new
                    {
                        src = resourcesSystemUrl + "uploads/images/" + extPath + newFileName,
                        title = "这是图片的标题啊。"
                    }
                });
            }
            catch (Exception ex)
            {

                var json = new
                {
                    code = 1,
                    msg = "出错了，错误信息：" + ex.Message
                };
                return Json(json);
            }
        }

    }
}
